<script setup lang="ts">
import Tools from '@/utils/tools';
import UserRequest from '@/request/userRequest';
import { navigate } from '@/utils/navigate';
import { APP_ID, APP_NAME } from '@/config/app';
import to from '@/utils/to';
import useAppStore from '@/store/modules/app';
import useToast from '@/hooks/useToast';

const checked = ref(false);
const { showToast } = useToast();
const path = ref<string>('/pages/home/index');

onLoad((options) => {
  if (options?.path) path.value = decodeURIComponent(options.path);
});

// 一键登录点击事件
const handleQuickLogin = async (event: any) => {
  if (!checked.value) {
    await showToast('请先阅读协议');
    return;
  }
  const openId = await Tools.getWechatLoginCode();
  const { code } = event.detail;
  const [err, res] = await to(UserRequest.GetPhone({ code, appId: APP_ID, hasLoading: true }));
  if (err) {
    await showToast('获取手机号失败，请重试');
    return;
  }
  UserRequest.Login({ userName: res.data, openId, loginType: 12, appId: APP_ID, tenantId: '1510456530575347712', userRole: 2, hasLoading: true }).then((res) => {
    useAppStore().$patch({ token: res.data.userCode, userInfo: res.data });
    useAppStore().connectSocketMessage();
    showToast('登录成功', 'success').then(() => {
      setTimeout(() => {
        navigate({ type: 'reLaunch', url: path.value });
      }, 500);
    });
  });
};

// 其它手机号登录
const handleGotoSmsCaptchaLoginPage = () => {
  if (!checked.value) {
    showToast('请先阅读协议');
    return;
  }
  navigate({ url: `/subcontract/person/login/SmsCaptchaLogin?path=${encodeURIComponent(path.value)}` });
};
</script>

<template>
  <view class="flex flex-col items-center p-5 bg-white h-screen">
    <view class="mt-20 w-[80px] h-[80px] bg-[#b7b7b7] rd-[50%] flex justify-center items-center">
      <i class="i-fluent:person-20-filled bg-[white] text-[39px]"></i>
    </view>

    <van-button v-if="checked" type="primary" :color="'#ffc300'" open-type="getPhoneNumber" @getphonenumber="handleQuickLogin" block class="mt-20 my-4 w-[100%]"> 手机号一键登录 </van-button>
    <van-button v-else type="primary" :color="'#ffc300'" block class="mt-20 my-4 w-[100%]" @click="handleQuickLogin"> 手机号一键登录 </van-button>
    <van-button class="w-[100%] rd-lg" plain block @tap="handleGotoSmsCaptchaLoginPage"> 其它手机号登录 </van-button>

    <view class="flex items-center mt-5 text-sm c-text-color-grey">
      <van-checkbox :checked-color="'#ffc300'" :value="checked" @change="checked = !checked">
        <text class="c-text-color-grey text-[12px]">我已阅读并同意</text>
        <text class="text-orange-500 ml-1 text-[12px]" @tap.stop="navigate({ url: '/subcontract/person/login/ServiceAgreement' })">《智慧呼叫用户服务协议》</text>
        <text class="c-text-color-grey text-[12px]">,并授权{{ APP_NAME }}使用该账号信息（如昵称头像、收货地址）</text>
      </van-checkbox>
    </view>
  </view>
</template>
